# -*- coding: utf-8 -*-
import argparse
from flask import Flask, jsonify
import subprocess
from flask import Flask
import signal
import os
from threading import Lock
import sys

#from flask_run import app
from tools.logger import log # 导入封装的logger方法

# 修复路径问题
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, BASE_DIR)

app = Flask(__name__)


# 全局变量
process = None
process_lock = Lock()



def validate_script():
  """检查run.py是否存在且可执行"""
  if not os.path.exists('run.py'):
    raise FileNotFoundError("run.py 文件不存在")
  if not os.access('run.py', os.X_OK):
    raise PermissionError("run.py 没有执行权限")


@app.route('/start', methods=['POST'])
def start_script():
  """启动run.py脚本"""
  global process

  try:
    validate_script()
    validate_script()

    with process_lock:
      if process is not None and process.poll() is None:
        return jsonify({
          'status': 'error',
          'message': '脚本已在运行中',
          'pid': process.pid
        }), 400

      try:
        process = subprocess.Popen(
          ['python', 'run.py'],
          stdout=subprocess.PIPE,
          stderr=subprocess.PIPE,
          text=True
        )
        log.info(f"成功启动脚本，PID: {process.pid}")
        log.info(f"After starting process, process object: {process}, PID: {process.pid if process else None}")
        # 等待脚本执行完成，获取输出
        stdout, stderr = process.communicate()
        if stderr:
          log.error(f"run.py 脚本执行出错，错误信息: {stderr}")
          return jsonify({
            'status': 'error',
            'message': f'run.py 脚本执行出错，错误信息: {stderr}'
          }), 500
        return jsonify({
          'status': 'success',
          'message': '脚本启动成功',
          'pid': process.pid
        })
      except Exception as e:
        log.error(f"启动脚本失败: {str(e)}", exc_info=True)
        return jsonify({
          'status': 'error',
          'message': f'启动脚本失败: {str(e)}'
        }), 500

  except Exception as e:
    log.error(f"脚本验证失败: {str(e)}", exc_info=True)
    return jsonify({
      'status': 'error',
      'message': f'脚本验证失败: {str(e)}'
    }), 400


@app.route('/stop', methods=['POST'])
def stop_script():
  """停止run.py脚本"""
  global process

  # with process_lock:
  if process is None or process.poll() is not None:
    log.info("Process is not running.")
    return jsonify({
      'status': 'error',
      'message': '没有正在运行的脚本'
    }), 400

  try:
    # 先尝试优雅终止
    log.info("尝试优雅终止进程")
    process.terminate()
    try:
      process.wait(timeout=5)
      log.info(f"脚本(PID: {process.pid})已正常终止")
    except subprocess.TimeoutExpired:
      # 如果超时，强制终止
      log.info("优雅终止超时，尝试强制终止进程")
      process.kill()
      log.warning(f"脚本(PID: {process.pid})被强制终止")

    process = None

    return jsonify({
      'status': 'success',
      'message': '脚本已停止'
    })
  except Exception as e:
    log.error(f"停止脚本失败: {str(e)}", exc_info=True)
    return jsonify({
      'status': 'error',
      'message': f'停止脚本失败: {str(e)}'
    }), 500


@app.route('/status', methods=['GET'])
def script_status():
  """获取脚本运行状态"""
  global process

  with process_lock:
    if process is None:
      return jsonify({
        'status': 'stopped',
        'message': '脚本未运行'
      })

    return_code = process.poll()
    if return_code is None:
      # 脚本仍在运行
      return jsonify({
        'status': 'running',
        'pid': process.pid,
        'message': '脚本正在运行'
      })
    else:
      # 脚本已结束
      return jsonify({
        'status': 'stopped',
        'exit_code': return_code,
        'message': f'脚本已结束，退出码: {return_code}'
      })


@app.route('/output', methods=['GET'])
def script_output():
  """获取脚本输出"""
  global process

  with process_lock:
    if process is None:
      return jsonify({
        'status': 'error',
        'message': '没有正在运行的脚本'
      }), 400

    try:
      stdout, stderr = process.communicate(timeout=1)
      return jsonify({
        'status': 'success',
        'stdout': stdout,
        'stderr': stderr
      })
    except subprocess.TimeoutExpired:
      # 脚本仍在运行，没有新输出
      return jsonify({
        'status': 'running',
        'message': '脚本仍在运行，无新输出'
      })
    except Exception as e:
      log.error(f"获取脚本输出失败: {str(e)}", exc_info=True)
      return jsonify({
        'status': 'error',
        'message': f'获取脚本输出失败: {str(e)}'
      }), 500


if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Run Flask app to control run.py script.')
  parser.add_argument('--port', type=int, default=8087, help='Port to run the application on')
  args = parser.parse_args()
  # 调试信息
  print("=== 工作目录 ===")
  print(os.getcwd())

  print("\n=== 路由表 ===")
  for rule in app.url_map.iter_rules():
    print(f"{rule.methods}: {rule}")

  try:
    log.info(f"Starting Flask application on port {args.port}")
    app.run(host='0.0.0.0', port=args.port)
  except Exception as e:
    log.error(f"Failed to start Flask application: {str(e)}", exc_info=True)
